<?php

namespace backend\controllers;

use app\models\ArcAndroid;
use app\models\ArcTrain;
use common\helps\Event;
use common\helps\Foo;
use common\helps\Tools;
use Yii;
use yii\data\Pagination;
use yii\helpers\Url;
use yii\web\Controller;

class CommonController extends Controller {

	//项目在服务器的绝对根路径
	public $absBasePath = '';
	//项目的文件相对路径的地址，比如为/advanced/backend/web
	public $url_base = '';
	//vender的相对路径
	public $rel_vender_path = '';
	//vender的adminlte的浏览器的adminlte的相对路径
	public $adminlte = '';
	//vender的adminlte的浏览器的组建的相对路径
	public $rel_vaabc_path = '';

	/**
	 * 权限的之前进行权限的验证，没有权限的不能访问相应的模块
	 *
	 * {@inheritdoc}
	 *
	 * @see \yii\web\Controller::beforeAction()
	 */
	public function beforeAction($action) {
        date_default_timezone_set('PRC');//设置时间时区为中国
        header("Content-type: text/html; charset=utf-8");//设置格式为utf-8
		$this->parmsInit();
		$action = Yii::$app->controller->action->id;
		$controller = Yii::$app->controller->id;
		$permissionName = '/'.$controller.'/'.$action;
// 		if (!Yii::$app->user->can($permissionName)
// 				&& Yii::$app->getErrorHandler()->exception === null
// 				&& !Yii::$app->user->isGuest) {
// 			//有权限访问该模块
// 			//表示没有权限访问该页面的模块，显示错误的页面
// 			ob_start();
// 			ob_clean();
// 			echo $this->render('@app/views/common/error');
// 			flush();
// 			exit();
// 		}else{
			return true;
// 		}
	}

	/**
	 * 参数的初始化
	 */
	public function parmsInit(){
		// 初始化项目的绝对根路径，比如E:/program/phpService/www
		$this->absBasePath = Yii::$app->basePath;
		//项目的文件相对路径的地址，比如为/advanced/backend/web
		$this->url_base = Url::base();
		$last = '..'.DIRECTORY_SEPARATOR;
		$ds = DIRECTORY_SEPARATOR;
		//vender的相对路径
		$this->rel_vender_path = ($this->url_base)
			.$ds.$last.$last.'vendor'.$ds;
		//vender的adminlte的浏览器的adminlte的相对路径
		$this->adminlte = $this->rel_vender_path.'almasaeed2010'.$ds.'adminlte'.$ds;
		//vender的adminlte的浏览器的组建的相对路径
		$this->rel_vaabc_path = $this->adminlte.'bower_components'.$ds;
	}


    /**
     * 公共的显示以及下载的按钮
     * @return string
     */
    public function actionPlayDownload(){
	    $this->layout = false;
        $httpFilePath = $_GET['httpFilePath'];
//        $tempFilePath = "/temp/".basename($httpFilePath).".mp3";
//        if(!file_exists(".".$tempFilePath)){
//            exec("java -jar ./asr/windows/Wav2Mp3.jar .".$httpFilePath." .".$tempFilePath);
//        }
        return $this->render('play-download',
            [
                'httpFilePath'=>$httpFilePath,
            ]
        );
    }

    /**
     * 公共的
     * @return string
     */
//    public function actionArcOneSyncAli(){
//        $filepath = $_GET['httpFilePath'];
//        $filepath = str_replace('\\','/',$filepath);
//        $build_oreder_one = Tools::build_oreder_one();
//        if(isset($_COOKIE['build_oreder_one'])){//如果没有cookie的话就设置cookie
//            $build_oreder_one = $_COOKIE['build_oreder_one'];
//        }else{
//            Yii::$app->response->cookies->add(new \yii\web\Cookie([
//                'name'=>'build_oreder_one',
//                'value'=>$build_oreder_one,
//                'httpOnly'=>false
//            ]));
//        }
//        $baseName = basename($filepath);
//        $tempPath = "/temp/".$baseName.".pcm";
//        $enCode = "ffmpeg -y -i .".$filepath." -acodec pcm_s16le -f s16le -ac 1 -ar 16000 .".$tempPath;
//        exec($enCode);
//        $command1 = "cd ./asr/linux-cpp-sdk.3.0.3.v3/sample/asrDemo2/run;
//            ./asrDemo ".$tempPath.",".$build_oreder_one.",http://192.168.2.117/common/check?user_id=".$build_oreder_one.";";
//        $command1 = str_replace('\\','/',$command1);
//        Foo::foo($command1);
//    }

    /**
     * 公共的非异步linux
     * @return string
     */
    public function actionArcOneSyncBaidu($filepath,$parms,$arcTrainModel=null){
        if(file_exists(".".$filepath)){
            $filepath = str_replace('\\','/',$filepath);
            $build_oreder_one = Tools::build_oreder_one();
            if(isset($_COOKIE['build_oreder_one'])){//如果没有cookie的话就设置cookie
                $build_oreder_one = Yii::$app->request->cookies->getValue('build_oreder_one');
            }else{
                Yii::$app->response->cookies->add(new \yii\web\Cookie([
                    'name'=>'build_oreder_one',
                    'value'=>$build_oreder_one,
                    'httpOnly'=>false
                ]));
            }
            $baseName = basename($filepath);
            $tempPath = "/temp/".$baseName.".pcm";
            $enCode = "ffmpeg -y -i .".$filepath." -acodec pcm_s16le -f s16le -ac 1 -ar 16000 .".$tempPath;
            exec($enCode);
//            $wavDuration = (int)Tools::getWavLength(".".$filepath);
            $wavDuration = 0;
//            if(v_result.size()>0){file_name = v_result[0];cout<<file_name<<endl;};//为文件路径
//            if(v_result.size()>1){user_id = v_result[1];cout<<user_id<<endl;};//为文件用户唯一的id,后面变为用户单独产生的随机唯一值
//            if(v_result.size()>2){sleep_ms = atoi(v_result[2].c_str());cout<<sleep_ms<<endl;};//为需要睡眠的时间长短
//            if(v_result.size()>3){vad_pause_time_ms = atoi(v_result[3].c_str());cout<<vad_pause_time_ms<<endl;};//设置vad语句静音切分门限, ms。 即原始语音静音 700ms后，SDK认为一句话结束
//            if(v_result.size()>4){host_api = v_result[4];cout<<host_api<<endl;};//为c++需要发送到的主机
//            if(v_result.size()>5){app_id = v_result[5];cout<<app_id<<endl;};//为文件用户唯一的app_id
//            if(v_result.size()>6){app_key = v_result[6];cout<<app_key<<endl;};//个为文件用户唯一的app_key
//            if(v_result.size()>7){app_secret = v_result[7];cout<<app_secret<<endl;};//为文件用户唯一的app_secret
//            if(v_result.size()>8){product_id = v_result[8];cout<<product_id<<endl;};//为文件用户唯一的product_id
            $file_name = $tempPath;
            $user_id = $build_oreder_one;
            $sleep_ms = $wavDuration;
            $vad_pause_time_ms = 100;
            $arc_train = ArcTrain::findOne($parms['arc_train']);
            $arc_android = $arc_train->arc_android;
            $arc_android_parms = ArcAndroid::findOne($arc_android)->parms;
            $arc_android_parms = str_replace("'","\"",$arc_android_parms);
            $arc_android_arr = json_decode($arc_android_parms);

            $host_api = $arc_android_arr->http."/common/check?user_id=".$build_oreder_one;
//            $app_id = "11212727";
//            $app_key = "rBrmHNGosSnezED1E88pTPTu";
//            $app_secret = "e3f2bd3fa3a87462b468cd12d052281f";
            $app_id = $arc_android_arr->app_id;
            $app_key = $arc_android_arr->app_key;
            $app_secret = $arc_android_arr->app_secret;
            $product_id = $arc_android_arr->product_id;
            $toCparms = $file_name.",".$user_id.",".$sleep_ms.",".$vad_pause_time_ms.",".$host_api.",".$app_id.",".$app_key.",".$app_secret.",".$product_id;
            $command1 = "cd ./asr/linux-cpp-sdk.3.0.3.v3/sample/asrDemo2/run;./asrDemo ".$toCparms.";";
            $command1 = str_replace(    '\\','/',$command1);
            $foo = new Foo();
            $foo->fooBaidu($command1,$parms,$arcTrainModel);
        }else{
            $foo = new Foo();
            $foo->saveToSql("",$parms);
        }
    }

    /**
     * 公共的非异步Windows
     * @return string
     */
    public function actionArcOneSyncAli($filepath,$parms,$arcTrainModel=null){
        if(file_exists($filepath)){
            $build_oreder_one = Tools::build_oreder_one();
            if(isset($_COOKIE['build_oreder_one'])){//如果没有cookie的话就设置cookie
                $build_oreder_one = Yii::$app->request->cookies->getValue('build_oreder_one');
            }else{
                Yii::$app->response->cookies->add(new \yii\web\Cookie([
                    'name'=>'build_oreder_one',
                    'value'=>$build_oreder_one,
                    'httpOnly'=>false
                ]));
            }
            $baseName = basename($filepath);
            $tempPath = "./temp/".$baseName;
            exec("java -jar ./asr/windows/Wav2Wav.jar ".$filepath." ".$tempPath);
            $arc_train = ArcTrain::findOne($parms['arc_train']);
            $arc_android = $arc_train->arc_android;
            $arc_android_parms = ArcAndroid::findOne($arc_android)->parms;
//            {'akId':'LTAIbgFM5AZELa73','akSecret':'fAJwUawP392rAiDRtQ70TT6EQyhcix'}
            $arc_android_parms = str_replace("'","\"",$arc_android_parms);
            $arc_android_arr = json_decode($arc_android_parms);

            $appKey = $arc_android_arr->appKey;
            $akId = $arc_android_arr->akId;
            $akSecret = $arc_android_arr->akSecret;
            $toCparms = $appKey." ".$akId." ".$akSecret." ".$tempPath;
            $command1 = "java -jar ./asr/windows/asr.jar ".$toCparms;
            $command1 = str_replace(    '\\','/',$command1);
            $parms['tempPath'] = $tempPath;
            $foo = new Foo();
            $foo->fooAli($command1,$parms,$arcTrainModel);
        }else{
            $foo = new Foo();
            $foo->saveToSql("",$parms);
        }
    }

    /**
     * 公共的非异步Windows
     * @return string
     */
    public function actionArcOneSyncAliContinue($filepath,$parms,$arcTrainModel=null){
        if(file_exists($filepath)){
            $build_oreder_one = Tools::build_oreder_one();
            if(isset($_COOKIE['build_oreder_one'])){//如果没有cookie的话就设置cookie
                $build_oreder_one = Yii::$app->request->cookies->getValue('build_oreder_one');
            }else{
                Yii::$app->response->cookies->add(new \yii\web\Cookie([
                    'name'=>'build_oreder_one',
                    'value'=>$build_oreder_one,
                    'httpOnly'=>false
                ]));
            }
            $baseName = basename($filepath);
            $tempPath = "./temp/".$baseName;
            exec("java -jar ./asr/windows/Wav2Wav.jar ".$filepath." ".$tempPath);
            $arc_train = ArcTrain::findOne($parms['arc_train']);
            $arc_android = $arc_train->arc_android;
            $arc_android_parms = ArcAndroid::findOne($arc_android)->parms;
//            {'akId':'LTAIbgFM5AZELa73','akSecret':'fAJwUawP392rAiDRtQ70TT6EQyhcix'}
            $arc_android_parms = str_replace("'","\"",$arc_android_parms);
            $arc_android_arr = json_decode($arc_android_parms);

            $appKey = $arc_android_arr->appKey;
            $akId = $arc_android_arr->akId;
            $akSecret = $arc_android_arr->akSecret;
            $toCparms = $appKey." ".$akId." ".$akSecret." ".$tempPath;
            $command1 = "java -jar ./asr/windows/asr.jar ".$toCparms;
            $command1 = str_replace(    '\\','/',$command1);
            $parms['tempPath'] = $tempPath;
            $foo = new Foo();
            $foo->fooAliContinue($command1,$parms,$arcTrainModel);
        }else{
            $foo = new Foo();
            $foo->saveToSql("",$parms);
        }
    }


    public function actionCheck(){
        $res = array_keys($_POST["{\"results_recognition\":"])[0];
        $user_id = $_GET["user_id"];
        $file = './assets/public/component/global-veriable/veriable_'.$user_id.'.php';
        if(!file_exists($file)){
            $myfile = fopen($file,"w");
            fwrite($myfile,"{\"start\":\"1\"}");
            fclose($myfile);
        }
        $fileContent = file_get_contents($file);
        $var = json_decode($fileContent);
        $var->$user_id = $res;
        $string = json_encode($var);
        $myfile = fopen($file, "w")or die("Unable to open file!");
        fwrite($myfile, $string);
        fclose($myfile);
        if($_GET['end'] != "" || $_GET['end']!=null){//删除生成的录音的中间文件,并且向数据库写数据
            //将产生的最终结果保存到数据库
            $tempFile = '';
            setcookie("asr_end",$_GET['end']);
            if(file_exists($tempFile)) {
                if (!unlink($tempFile)) {
                    echo("删除文件" . $tempFile . "失败！");
                }else{
                    echo("删除文件" . $tempFile . "成功！");
                }
            }
        }else{
            setcookie("asr_end","");
        }


    }

    /**
     * 识别内容页面
     */
    public function actionIdentifyResult()
    {
        $this->layout = false;
        //接受c++ 传过来的结果
        $build_oreder_one = $_COOKIE['build_oreder_one'];
        try{
            $file = './assets/public/component/global-veriable/veriable_'.$build_oreder_one.'.php';
            if(file_exists($file)){
                $fileContent = file_get_contents($file);
                $var = json_decode($fileContent);
                $user_id = $_COOKIE['build_oreder_one'];
                $asr_res = $var->$user_id;
            }
        }catch (\Exception $e){
            var_dump($e);
        }
        $arr = explode(",",$asr_res);
        return $this->render('identify-result',['arr'=>$arr]);
    }


    /**
     * 分页的功能操作
     */
    protected function pagesDo($dataProvider){
        $query = $dataProvider->query;
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(                                                                                                                            )]);
        if (isset($_POST['pageSize'])) {//设置了参数，就把参数给pageSize session
            setcookie('pageSize', $_POST['pageSize']);
        }
        if (!empty($_COOKIE['pageSize'])) {
            $pages->pageSize = (int)$_COOKIE['pageSize'];
        } else {
            $pages->pageSize = 5;
        }
        $dataProvider->pagination = $pages;
    }
}